package com.autotest.sync.android;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import com.google.common.eventbus.AsyncEventBus;
/**
 * 自定义事件总线，用于进行命令相关发送
 * @author zy
 *
 */
public class MyEventBus {
	private static MyEventBus instance = null;
	private static ConcurrentHashMap<String, SlaveDevice> mSlaveDevices = new ConcurrentHashMap<String, SlaveDevice>();
	private AsyncEventBus mEventBus = null;
	
	private MyEventBus(){
		mEventBus = new AsyncEventBus(Executors.newCachedThreadPool());
	}
	
	public static MyEventBus getInstance(){
		if(instance == null){
			synchronized (MyEventBus.class) {
				instance = new MyEventBus();
			}
		}
		return instance;
	}
	
	public void register(SlaveDevice obj){
		mSlaveDevices.put(obj.serial, obj);
		mEventBus.register(obj);
	}
	
	public void register(Object obj){
		mEventBus.register(obj);
	}
	
	public void unRegister(Object obj){
		if(obj instanceof String){
			if(mSlaveDevices.containsKey(obj)){
				mEventBus.unregister(mSlaveDevices.get(obj));
				mSlaveDevices.remove(obj);
				obj = null;
			}
		}else{
			String serial = ((SlaveDevice)obj).serial;
			mSlaveDevices.remove(serial);
			mEventBus.unregister(obj);
			obj = null;
		}
	}
	
	public void clear(){
		for(SlaveDevice syncdevice: mSlaveDevices.values()){
			mEventBus.unregister(syncdevice);
		}
		mSlaveDevices.clear();
	}
	
	public void post(Object obj){
		mEventBus.post(obj);
	}
}
